人臉比對
import requests
from json import JSONDecoder
定義一個函數,用於比較兩個圖像的人臉相似度
def compareimage(filepath1 ,filepath2): #人臉比對
try:
http_url = "https://api-cn.faceplusplus.com/facepp/v3/compare"
key = "****" #輸入你的API Key
secret = "****" #輸入你的 API Secret
data = {"api_key":key, "api_secret": secret}
files = {"image_file1": open(filepath1, "rb"),"image_file2": open(filepath2, "rb")} #打開兩個圖像文件
response = requests.post(http_url, data=data, files=files) #進行辨識
req_con = response.content.decode('utf-8') #取得結果
req_dict = JSONDecoder().decode(req_con) #將結果轉為字典
confidence = req_dict['confidence'] #取得相似度
return confidence
except Exception as e:
print("無法識別!")
return 0
比較兩個圖像中的人臉相似度並顯示結果
def showcompare(filepath1 ,filepath2):
result = compareimage(filepath1 ,filepath2)
print('相似度指數=' + str(result))
if result >= 75:
print(filepath1+' 和 '+filepath2+' 為同一人!')
else:
print(filepath1+' 和 '+filepath2+' 為不同人!')
showcompare('/content/David1.jpg', '/content/face1.jpg') #放入要比對照片的路徑
showcompare('/content/jeng1.jpg', '/content/face1.jpg') #放入要比對照片的路徑
接下來要做會員登入的人臉比對,若是會員就可以成功登入,若不是就會登入失敗。
import requests
from json import JSONDecoder
def compareimage(filepath1 ,filepath2): #人臉比對
try:
http_url = "https://api-cn.faceplusplus.com/facepp/v3/compare"
key = "GwO1Ty6a0PPeWBUjjnu3yc9H_ml2LyuO"
secret = "xb4BYlAEHXC9CbQ8Yx1v5iKuryJCk8da"
data = {"api_key":key, "api_secret": secret}
files = {"image_file1": open(filepath1, "rb"),"image_file2": open(filepath2, "rb")}
response = requests.post(http_url, data=data, files=files) #進行辨識
req_con = response.content.decode('utf-8') #取得結果
req_dict = JSONDecoder().decode(req_con) #將結果轉為字典
confidence = req_dict['confidence'] #取得相似度指數
return confidence
except Exception:
print("無法識別!")
return 0
def login(filepath):
success = False
for img in imagelibrary: #逐一比對
print(imagelibrary[img]) #顯示比對對象
if compareimage(imagelibrary[img], filepath) >= 75:
print('登入成功!你是:', img)
success = True
break
if not success: #如果全部比對失敗
print('登入失敗!')
#會員集字典
imagelibrary ={"Lily": "/content/Lily.jpg",
"David": "/content/David.jpg",
"Cynthia": "/content/Cynthia.jpg",
"Bear": "/content/Bear.jpg",
"jeng": "/content/jeng.jpg"}
login('/content/face2.jpg')
login('/content/emmy1.jpg')
---20231011---